<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/10/30
 * Time: 下午1:50
 */

namespace App\Models;

use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;

class MobilePay extends Model
{
    protected $table = 'pay';

    public $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function rechargeOrder()
    {
        return $this->hasOne(RechargeOrder::class);
    }

    public static function setPaid(Pay $pay)
    {
        try {
            DB::beginTransaction();

            $pay->is_paid = 1;
            $pay->paid_at = Carbon::now()->toDateTimeString();
            $pay->save();

            //首次充值赠送88元优惠券
            $order = $pay->rechargeOrder;
            $user = DB::table('recharge_order')->where('status','>',0)->where('user_id',$order->user_id)->get();
            if ($user->count() == 0){
                $regCouponIds = Configure::rechargeCoupon();
                if ($regCouponIds) {
                    foreach ($regCouponIds as $couponId) {
                        UserCoupon::sendToUser($couponId, $order->user_id);
                    }
                }
            }

            if ($pay->rechargeOrder) {
                $order->status  = RechargeOrder::STATUS_PAID;
                $order->paid_at = Carbon::now()->toDateTimeString();
                $order->save();
                //成功支付后修改优惠券状态
                DB::update('update yk_user_coupon set status = 2 where id = ?', [$order->coupon_id]);

                //判断油是否存在
                $users = DB::table('oil_card')->where('card_no',$order->oil_card_id)->get();
                if (empty($users)){
                    return fail(400, '卡号不存在');
                }
                // 生成充值明细
                if ($order->months == 1 && $order->type == 1) {    //一个月套餐充值
                        $payAt = Carbon::parse('+1 months')->toDateTimeString();
                    }

                if ($order->type == RechargeOrder::TYPE_RECHARGE) {
                    for ($i = 1; $i <= $order->months; $i++) {
                        if ($i == 1 && $order->type == 2) {
                            $payAt = Carbon::now()->toDateTimeString();// 一个月即时充值
                        } else {
                            $payAt = Carbon::now()->addMonths($i-1)->toDateTimeString();// N个月套餐充值
                        }

                        $detail = RechargeOrderDetail::create([
                            'recharge_order_id' => $order->id,
                            'current_month'     => $i,
                            'total_month'       => $order->months,
                            'user_id'           => $order->user_id,
                            'oil_card_id'       => $order->oil_card_id,
                            'amount'            => $order->recharge_amount,
                            'pay_at'            => $payAt,
                        ]);

                        // 创建充值任务
                        RechargeTask::createTask($order->oilCard, $detail->amount, $payAt, $order->id, $detail->id);

                    }

                    // 更新用户充值及待充金额
                    $order->user->recharge_amount += (float) ($order->recharge_amount * $order->months);
                    $order->user->pending_amount += (float) ($order->recharge_amount * $order->months);
                    $order->user->save();
                } else {
                    // 创建充值任务
                    $payAt = Carbon::now()->toDateTimeString();
                    RechargeTask::createTask($order->oilCard, $order->recharge_amount, $payAt, $order->id);

                    // 更新用户充值及待充金额
                    $order->user->recharge_amount += (float) ($order->recharge_amount);
                    $order->user->pending_amount += (float) ($order->recharge_amount);
                    $order->user->save();
                }
            }

            DB::commit();

        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            throw new \Exception('订单支付出错啦');
        }
    }

    public static function alipay(Pay $pay)
    {
        // 创建支付单。
        $alipay = app('alipay.mobile');
        $alipay->setOutTradeNo($pay->pay_sn);
        $alipay->setTotalFee($pay->amount);
        $alipay->setSubject('充值订单');
        $alipay->setBody('充值订单'. $pay->amount . '元');

        // 返回签名后的支付参数给支付宝移动端的SDK。
        return $alipay->getPayPara();
    }

    public static function weixinApp(Pay $pay)
    {
        $app = Factory::payment(config('wechat.app_pay'));
        $str = '1234567890';
        $shuffled = str_shuffle($str);
        $result = $app->order->unify([
            'body' => '充值订单'. $pay->amount . '元',
            'out_trade_no' => $shuffled,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'APP', // 请对应换成你的支付方式对应的值类型
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->appConfig($result['prepay_id']);
        }
        return $result;
    }

    public static function weixin(Pay $pay, $openId)
    {
        $app = Factory::payment(config('wechat.wx_pay'));
        $str = '1234567890';
        $shuffled = str_shuffle($str);
        $result = $app->order->unify([
            'body' => '充值订单'. $pay->amount . '元',
            'out_trade_no' => $shuffled,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openId,
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->bridgeConfig($result['prepay_id']);
        }
        return $result;
    }
}